Zepto(function($) {
    var user_id = $('#hidden_user').val()

    $("input[type='search']").keydown(function(e) {
        if (e.keyCode === 13 && delivery_list_vm.search_word) {
            showChooseModal();
        }
    });

    $("input[type='search']").focusin(function(e) {
        showSearch();
    });

    $("input[type='search']").focusout(function(e) {
        hideSearch();
    });

    function showSearch() {
        toggleSearch($('.search-metal'), 'show');
    };

    function hideSearch() {
        toggleSearch($('.search-metal'), 'hide');
    };

    function refresh_search_word(search_type) {
        delivery_list_vm.search_type = search_type;
        if (search_type === 'partner') delivery_list_vm.search_word_display = '客户';
        else if (search_type === 'picking') delivery_list_vm.search_word_display = '单据';
        else if (search_type === 'all') delivery_list_vm.search_word_display = '全部';
    }

    function toggleSearch(ele, direction, time) {

        if (!delivery_list_vm.search_word && direction === 'show') return;

        if (!time) time = 500;
        if (!direction) direction = 'hide';

        if (direction === 'show') {
            if (ele.css('display') == 'none') ele.css('display', 'block');
            else return;
        };

        var start = (new Date()).getTime();
        animate();

        function animate() {
            var now = (new Date()).getTime();
            var elapsed = now - start;
            var fraction = elapsed / time;

            if (fraction < 1) {
                var x = (direction === 'hide')? Math.cos(fraction * 0.5 * Math.PI) : Math.sin(fraction * 0.5 * Math.PI);
                ele.css('opacity', x);
                setTimeout(animate, Math.min(25, time - elapsed));
            } else {
                if (direction === 'hide') {
                    ele.css('display', 'none');
                };
            };
        };
    };

    function showChooseModal() {
        hideSearch();
        if (delivery_list_vm.search_word) {
            $.get('/weixin/delivery/get_pickings_by_search', {
                search_word: delivery_list_vm.search_word, search_type: delivery_list_vm.search_type
            }, function(e) {
                var response = JSON.parse(e);
                if (response.length !== 0) {
                    delivery_list_vm.search_pickings = response;
                    delivery_list_vm.choose_metal = true;
                    toggleSearch($('#picking-choose-metal'), 'show');
                } else {
                    $.alert('抱歉，没有找到有效的单据，请重新搜索');
                };
            });
        };
    };

    function hideChooseModal() {
        delivery_list_vm.choose_metal = false;
        toggleSearch($('#picking-choose-metal'), 'hide');
    };

    var get_location = function() {
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                $.ajax({
                    url: '/weixin/delivery/update_location',
                    data: {user_id: user_id, latitude: res.latitude, longitude: res.longitude, speed: res.speed, accuracy: res.accuracy},
                    type: 'post',
                    async: true,
                })
            },
        });
    };

    //暂时不记录位置信息
    //setInterval(get_location, 30000);

    var sync_content = function() {
        $.ajax({
            url: '/weixin/delivery/get_pickings',
            data: {user_id: user_id},
            success: function(e) {
                delivery_list_vm.pickings = JSON.parse(e);
            },
            type: 'get',
            async: true,
        });
    };

    var refresh_choose = function() {
        delivery_list_vm.some_choose = delivery_list_vm.pickings.some(function(picking) { return picking.choose } );
        delivery_list_vm.every_choose = delivery_list_vm.pickings.every(function(picking) { return picking.choose } );
    };

    var delivery_list_vm = avalon.define({
        $id: 'delivery-list',
        pickings: [],
        search_pickings: [],
        search_word: '',
        search_word_display: '全部',
        search_type: 'all',
        some_choose: false,
        every_choose: false,
        choose_metal: false,

        do_choose: function(word) {
            refresh_search_word(word);
            showChooseModal();
        },

        metal_cancel: function() {
            hideChooseModal();
        },

        metal_choose: function(picking) {
            picking.choose = !picking.choose;
        },

        metal_submit: function() {
            var submit_ids = [];
            delivery_list_vm.search_pickings.forEach(function(picking) {
                if (picking.choose) {
                    delivery_list_vm.pickings.push(picking);
                    submit_ids.push(picking.id);
                };
            });

            if (submit_ids.length > 0) {
                $.post('/weixin/delivery/submit', {picking_ids: JSON.stringify(submit_ids), user_id: user_id});
            };

            hideChooseModal();
        },

        display_detail: function(event, picking) {
            if (picking.lines.length == 0) {
                $.ajax({
                    url: '/weixin/delivery/get_lines',
                    data: {picking_id: picking.id},
                    success: function(e) {
                        picking.lines = JSON.parse(e);
                    },
                    type: 'get',
                    async: true,
                });
            };
            picking.is_display_detail = !picking.is_display_detail;
            event.stopPropagation();
        },

        choose: function(picking) {
            picking.choose = !picking.choose;
            refresh_choose();
        },

        all_choose: function() {
            delivery_list_vm.pickings.forEach(function(picking) { picking.choose = !delivery_list_vm.some_choose } );
            refresh_choose();
        },

        picking_done: function() {
            delivery_list_vm.pickings.forEach(function(picking) {
                if (picking.choose) {
                    picking.hidden = true;
                };
            });

            done_ids = delivery_list_vm.pickings.filter(function(picking) { return picking.choose }).map(function(picking) { return picking.id })

            if (done_ids.length > 0) {
                $.ajax({
                    url: '/weixin/delivery/picking_done',
                    data: {picking_ids: JSON.stringify(done_ids)},
                    success: function(e) {
                        $.toast('确认送货成功');
                    },
                    type: 'post',
                    async: true,
                });
            };
        },
    });

    delivery_list_vm.$watch('search_word', function(word) {
        if (word) {
            showSearch();
        } else {
            hideSearch();
        }
    });

    sync_content();
    avalon.scan();
});